package com.example.mobile2121606109ycg0614homework;

import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private RecyclerView vMainCars;
    private String url="http://10.160.123.3:8080/A/stage.json";
    OkHttpClient okHttpClient = new OkHttpClient();
    Gson gson = new Gson();
    Type type = new  TypeToken<List<Cars>>(){}.getType();
    List<Cars> newsList=new ArrayList<>();
    CarsRVAdapter castAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        vMainCars.setLayoutManager(new LinearLayoutManager(this));

        new Thread(new Runnable() {
            @Override
            public void run() {
                Request request = new Request.Builder()
                        .url(url)
                        .build();
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String result = response.body().string();
                        newsList=gson.fromJson(result, type);
                        Log.i("TAG", String.valueOf(newsList.size()));
                        castAdapter = new CarsRVAdapter(newsList);
                        runOnUiThread(new Runnable(){
                            @Override
                            public void run() {
                                vMainCars.setAdapter(castAdapter);
                            }
                        });
                    }

                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {

                    }
                });
            }
        }).start();
    }

    private void initView() {
        vMainCars = (RecyclerView) findViewById(R.id.vMainCars);
    }
}